<?php

namespace app\admin\logic;

use app\common\model\User;

/**
 * Class CarLogic
 * @package app\admin\logic
 *
 * 车辆管理
 * 车辆登陆
 */
class CarLogic {
	function findOne( $car_num ) {
		return model( 'car' )->find( $car_num );
	}

	/*
	 * 条件查询车辆
	 */
	function query( $where ) {
		return model( 'car' )->where( $where )->order('car_num')->select();
	}

	function queryJqGrid( $where = '', $page = 1, $rows = 20,$q='' ) {
		$car = model( 'car' );
		$param=json_decode($q,true);
		$conditions=[];
		if(!empty($param['car_num'])){
			$car_num=$param['car_num'];
			$conditions['car_num']=array('like',"%$car_num%");
		}
		if(!empty($param['car_type'])){
			$car_type=$param['car_type'];
			$conditions['car_type']=array('like',"%$car_type%");
		}
		if(!empty($param['vin'])){
			$vin=$param['vin'];
			$conditions['vin']=array('like',"%$vin%");
		}
		$pageInfo = $car->where( $where )->where($conditions)->paginate( $rows );
		//p($pageInfo);
		$data['total'] = $pageInfo->lastPage();
		$data['page']  = $pageInfo->currentPage();
		$data['rows']  = $pageInfo->items();

		return $data;
	}

	/*
	 * 新增车辆
	 */
	function add( $data ) {
		if ( ! empty( $data['car_num'] ) ) {
			$car = $this->findOne( $data['car_num'] );
			if ( $car ) {
				return model( 'car' )->data( $data )->allowField( true )->isUpdate( true )->save();
			} else {
				return model( 'car' )->data( $data )->allowField( true )->save();
			}
		}
	}

	function del( $car_num = '' ) {
		return model( 'car' )->destroy( $car_num );
	}

	public function getMoneyLog($page=1,$rows=10,$q='',$sidx='',$sord='') {
		$car = model( 'CarMoneyLog' );
		$param=json_decode($q,true);
		$conditions=[];
		$order='';
		if(!empty($param['car_num'])){
			$car_num=$param['car_num'];
			$conditions['car_num']=array('like',"%$car_num%");
		}
		if(!empty($param['operator.name'])){
			$operator=$param['operator.name'];
			$conditions['operator.name']=array('like',"%$operator%");
		}
		// if(!empty($param['vin'])){
		// 	$vin=$param['vin'];
		// 	$conditions['vin']=array('like',"%$vin%");
		// }
		if(!empty($sidx)){
			$order=$sidx.' '.$sord;
		}
		$pageInfo = $car->with('operator')->where($conditions)->order($order)->order('inserttime desc')->paginate( $rows );
		//p($pageInfo);
		$data['total'] = $pageInfo->lastPage();
		$data['page']  = $pageInfo->currentPage();
		$data['rows']  = $pageInfo->items();

		return $data;
	}


}
